const {jwtRouter} = require('../../util')
const router = jwtRouter()
const {query} = require('../../db')
const md5 = require('md5')
const {key} = require('../../config')

let tableName = 'users'

router.put('/', async (req, res, next)=>{

    let old_password = req.body.old_password
    let password = req.body.password

    let sql = `SELECT password FROM ${tableName} WHERE id = ?`
    let ret = await query(sql, req.userId).catch(next)
    if(ret === undefined) return 

    if(ret[0].password === md5(old_password + key)) {

        let newPassword = md5(password + key)

        sql = `UPDATE ${tableName} SET password=? WHERE id = ?`

        ret = await query(sql, [newPassword, req.userId]).catch(next)
        if(ret === undefined) return 

        res.json({
            'ok': 1
        })
    } else {
        res.json({
            'ok': 0,
            'error': '原密码不正确！'
        })
    }
})

module.exports = router